package com.hgicreate.app.md2docx.extension.kroki.internal;

import okhttp3.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class KrokiClient {
    private final String url = "http://localhost:8002/png";
    private final OkHttpClient client = new OkHttpClient().newBuilder()
            .build();
    private final MediaType mediaType = MediaType.parse("text/plain");

    public BufferedImage parse(String content) throws IOException {
        RequestBody body = RequestBody.create(mediaType, content);
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("Content-Type", "text/plain")
                .addHeader("Accept", "*/*")
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return ImageIO.read(response.body().byteStream());
            }
        }
        throw new IOException("转换失败: " + content);
    }

    public static void main(String[] args) throws IOException {
        KrokiClient krokiClient = new KrokiClient();
        String content = """
                xychart-beta
                    title "关键质量指标趋势（2021-2023）"
                    x-axis "年份" [2021, 2022, 2023]
                    y-axis "百分比" 90 --> 100
                    bar "客户满意度" [91.3, 94.7, 97.2]
                    line "系统可用率" [99.2, 99.5, 99.8]
                    line "故障修复及时率" [95.1, 97.6, 99.0]
                """;
        ImageIO.write(krokiClient.parse(content), "png", new File("./output.png"));
    }
}
